import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: () => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			return new Promise((resolve) => {
				setTimeout(() => {
					// 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
					const userName = Cookies.get('userName');
					const role = Cookies.get('role');
					//console.log("role: " + role);
					// 模拟数据
					let defaultRoles = [];
					let defaultAuthBtnList = [];
					// admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
					let adminRoles = ['admin'];
					let superAdminRoles = ['superAdmin'];
					let expertRoles = ['expert'];
					// admin 按钮权限标识
					let adminAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
					let superAdminAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
					let expertAuthBtnList = ['btn.add', 'btn.link'];
					// test 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
					let testRoles = ['common'];
					// test 按钮权限标识
					let testAuthBtnList = ['btn.add', 'btn.link'];
					// 不同用户模拟不同的用户权限
					if (role === 'admin') {
						defaultRoles = adminRoles;
						defaultAuthBtnList = adminAuthBtnList;
					} else if(role === 'superAdmin'){
						defaultRoles = superAdminRoles;
						defaultAuthBtnList = superAdminAuthBtnList;
					} else if(role === 'expert'){
						defaultRoles = expertRoles;
						defaultAuthBtnList = expertAuthBtnList;
					} else{
						defaultRoles = testRoles;
						defaultAuthBtnList = testAuthBtnList;
					}
					// 用户信息模拟数据
					const userInfos = {
						userName: userName,
						photo: Cookies.get('photo'),
						time: new Date().getTime(),
						roles: defaultRoles,
						authBtnList: defaultAuthBtnList,
					};
					resolve(userInfos);
				}, 0);
			});
		},
	},
});
